package org.spbsu.apco.server.taskset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spbsu.apco.server.broker.Broker;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.util.Assert;

import java.util.LinkedList;
import java.util.List;

/**
 * User: solozobov
 * Date: 20.11.12
 */

public class TaskSetEmitter {
    private static final Logger LOG = LoggerFactory.getLogger(TaskSetEmitter.class);
    public static final int TASKSET_UPDATE_INTERVAL = 100;

    private LinkedList<BaseTaskSet> orderedTaskSetList;

    private Broker broker;

    public void start() {
        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!orderedTaskSetList.isEmpty()) {
                    final BaseTaskSet currentTaskSet = orderedTaskSetList.removeFirst();
                    broker.addTaskSet(currentTaskSet);

                    while (!broker.isFinished(currentTaskSet)) {
                        try {
                            Thread.sleep(TASKSET_UPDATE_INTERVAL);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    LOG.info("TaskSet #{} finished!", new Object[]{currentTaskSet.getId()});
                    LOG.info(broker.getResults(currentTaskSet).toString());
                }
            }
        });
        thread.setDaemon(true);
        thread.start();
    }

    @Required
    public void setOrderedTaskSetList(final List<BaseTaskSet> orderedTaskSetList) {
        this.orderedTaskSetList = new LinkedList<BaseTaskSet>(orderedTaskSetList);
    }

    public void setBroker(final Broker broker) {
        Assert.isTrue(this.broker == null, "Broker should not be redefined: " + broker);
        this.broker = broker;
    }
}
